import { useUserStore, useUserStoreHook } from '@/store/system/user';
import { isIncludeAllChildren, isString, storageLocal } from '@pureadmin/utils';

export interface DataInfo<T> {
	/** 头像 */
	avatar?: string;
	/** 用户名 */
	username?: string;
	/** 昵称 */
	nickname?: string;
	/** 当前登录用户的角色 */
	roles?: Array<string>;
	/** 当前登录用户的按钮级别权限 */
	permissions?: Array<string>;
}

export const userKey = 'user-info';
/**
 * @description 设置用户信息
 */
export function setUserInfo(data: any) {
	const userStore = useUserStore();

	function setUserKey({ avatar, username, nickname, roles, permissions }) {
		userStore.avatar = avatar;
		userStore.username = username;
		userStore.nickname = nickname;
		userStore.roles = roles;
		userStore.permissions = permissions;
		storageLocal().setItem(userKey, { avatar, username, nickname, roles, permissions });
	}

	if (data.username && data.roles) {
		const { username, roles } = data;
		setUserKey({
			avatar: data?.avatar ?? '',
			username,
			nickname: data?.nickname ?? '',
			roles,
			permissions: data?.permissions ?? [],
		});
	} else {
		const avatar = storageLocal().getItem<DataInfo<number>>(userKey)?.avatar ?? '';
		const username = storageLocal().getItem<DataInfo<number>>(userKey)?.username ?? '';
		const nickname = storageLocal().getItem<DataInfo<number>>(userKey)?.nickname ?? '';
		const roles = storageLocal().getItem<DataInfo<number>>(userKey)?.roles ?? [];
		const permissions = storageLocal().getItem<DataInfo<number>>(userKey)?.permissions ?? [];
		setUserKey({ avatar, username, nickname, roles, permissions });
	}
}

/** 删除用户信息 */
export function removeUserInfo() {
	storageLocal().removeItem(userKey);
}

/** 是否有按钮级别的权限（根据登录接口返回的`permissions`字段进行判断）*/
export const hasPerms = (value: string | Array<string>): boolean => {
	if (!value) return false;
	const allPerms = '*:*:*';
	const { permissions } = useUserStoreHook();
	if (!permissions) return false;
	
	// 检查是否有全局权限'*'或'*:*:*'
	if (permissions.includes('*') || permissions.includes(allPerms)) return true;
	
	return isString(value) ? permissions.includes(value) : isIncludeAllChildren(value, permissions);
};
